<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能数据洞察与问卷管理平台</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #1890ff;
            --success-color: #52c41a;
            --error-color: #ff4d4f;
            --text-dark: #1f2d3d;
            --text-light: #5e6c84;
            --border-color: #e4e7ed;
            --shadow-default: 0 4px 12px rgba(0,0,0,0.08);
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            line-height: 1.5;
            margin: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
            max-width: 1200px;
            margin: 0 auto;
        }

        .sidebar {
            width: 240px;
            background: white;
            box-shadow: var(--shadow-default);
            padding: 20px 0;
        }

        .nav-title {
            color: var(--text-dark);
            font-size: 16px;
            padding: 12px 24px;
            font-weight: 600;
        }

        .main-content {
            flex: 1;
            padding: 32px;
            background: #f5f7fa;
        }

        .create-steps {
            display: flex;
            justify-content: center;
            gap: 48px;
            margin: 32px 0;
        }

        .step-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            opacity: 0.5;
        }

        .step-item.active {
            opacity: 1;
        }

        .step-icon {
            width: 48px;
            height: 48px;
            background: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }

        .drag-area {
            background: white;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: var(--shadow-default);
        }

        .drag-panel-title {
            color: var(--text-dark);
            font-size: 16px;
            margin-bottom: 16px;
            font-weight: 500;
        }

        .drag-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            margin: 8px 0;
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            cursor: move;
            transition: all 0.2s;
        }

        .drag-item:hover {
            border-color: var(--primary-color);
            box-shadow: var(--shadow-default);
        }

        .drag-item i {
            margin-right: 8px;
            color: var(--primary-color);
        }

        .edit-area {
            min-height: 400px;
            background: white;
            border-radius: 8px;
            padding: 24px;
            box-shadow: var(--shadow-default);
        }

        .question-card {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            transition: all 0.2s;
        }

        .question-card:hover {
            border-color: var(--primary-color);
        }

        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }

        .question-type {
            color: var(--primary-color);
            font-size: 14px;
            font-weight: 500;
        }

        .ant-btn {
            padding: 8px 16px;
            background: var(--primary-color);
            border: none;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .ant-btn:hover {
            background: #40a9ff;
            box-shadow: var(--shadow-default);
        }

        .question-input {
            width: 100%;
            padding: 8px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin-bottom: 12px;
        }
    </style>
</head>
<body>
    <!-- 登录状态检查 -->
    {% if not user.is_authenticated %}
    <script>
        alert('请先登录！');
        window.location.href = "{% url 'login' %}";
    </script>
    {% endif %}

    <div class="container">
        <div class="sidebar">
            <div class="nav-title">问卷组件库</div>
            <div class="drag-area">
                <div class="drag-item" draggable="true" data-type="singleChoice">
                    <i class="fas fa-dot-circle"></i> 单选题
                </div>
                <div class="drag-item" draggable="true" data-type="multipleChoice">
                    <i class="fas fa-check-square"></i> 多选题
                </div>
                <div class="drag-item" draggable="true" data-type="text">
                    <i class="fas fa-comment"></i> 文本题
                </div>
            </div>
        </div>

        <div class="main-content">
            <div class="drag-area">
                <h2 class="nav-title">创建新问卷</h2>

                <div class="create-steps">
                    <div class="step-item active" data-step="1">
                        <div class="step-icon">1</div>
                        <div>基础设置</div>
                    </div>
                    <div class="step-item" data-step="2">
                        <div class="step-icon">2</div>
                        <div>题目编辑</div>
                    </div>
                    <div class="step-item" data-step="3">
                        <div class="step-icon">3</div>
                        <div>发布设置</div>
                    </div>
                </div>

                <div class="edit-area" id="editArea">
                    <div class="drag-panel-title">编辑区域（拖入组件开始编辑）</div>
                </div>

                <div style="text-align: right; margin-top: 24px;">
                    <button class="ant-btn" onclick="saveSurvey()">
                        <i class="fas fa-save"></i> 保存问卷
                    </button>
                    <button class="ant-btn" style="margin-left: 12px;" onclick="publishSurvey()">
                        <i class="fas fa-share"></i> 发布问卷
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

    <script>
        // 拖拽功能实现
        document.addEventListener('dragstart', (e) => {
            if (e.target.classList.contains('drag-item')) {
                e.dataTransfer.setData('text/plain', e.target.dataset.type);
                e.dataTransfer.effectAllowed = 'move';
            }
        });

        document.addEventListener('dragover', (e) => e.preventDefault());

        document.addEventListener('drop', (e) => {
            e.preventDefault();
            const type = e.dataTransfer.getData('text/plain');
            if (e.target.closest('#editArea')) {
                addQuestion(type);
            }
        });

        // 问题管理功能
        function addQuestion(type) {
            const questionId = Date.now();
            const questionCard = document.createElement('div');
            questionCard.className = 'question-card';
            questionCard.id = questionId;
            questionCard.innerHTML = `
                <div class="question-header">
                    <span class="question-type">${getTypeName(type)}</span>
                    <button class="ant-btn" onclick="deleteQuestion('${questionId}')">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <input type="text" class="question-input" placeholder="请输入问题内容..." required>
                ${getOptionsHTML(type)}
            `;
            document.getElementById('editArea').appendChild(questionCard);
        }

        function getTypeName(type) {
            const typeMap = {
                singleChoice: '单选题',
                multipleChoice: '多选题',
                text: '文本题'
            };
            return typeMap[type] || '未知题型';
        }

        function getOptionsHTML(type) {
            if (type === 'text') {
                return '<textarea class="question-input" placeholder="文本输入区域..." rows="3" required></textarea>';
            }

            return `
                <div class="options">
                    ${Array.from({ length: 2 }, (_, i) => `
                        <div class="option-item">
                            <span>${i + 1}.</span>
                            <input type="text" class="question-input" placeholder="选项内容" required>
                        </div>
                    `).join('')}
                    <button type="button" class="ant-btn" onclick="addOption(this)">
                        <i class="fas fa-plus"></i> 添加选项
                    </button>
                </div>
            `;
        }

        function addOption(button) {
            const optionsContainer = button.previousElementSibling;
            const newOption = document.createElement('div');
            newOption.className = 'option-item';
            newOption.innerHTML = `
                <span>${optionsContainer.children.length + 1}.</span>
                <input type="text" class="question-input" placeholder="选项内容" required>
            `;
            optionsContainer.appendChild(newOption);
        }

        function deleteQuestion(id) {
            const element = document.getElementById(id);
            element?.remove();
        }

        // 数据存储功能
        function saveSurvey() {
    const questions = Array.from(document.querySelectorAll('.question-card')).map(card => {
        const typeText = card.querySelector('.question-type').textContent;
        // 将中文题型转换为英文标识
        const typeMap = {
            '单选题': 'singleChoice',
            '多选题': 'multipleChoice',
            '文本题': 'text'
        };
        const type = typeMap[typeText] || 'text'; // 默认 fallback 到 text
        return {
            type: type, // 保存英文标识
            question: card.querySelector('.question-input').value,
            options: Array.from(card.querySelectorAll('.option-item input')).map(i => i.value)
        };
    });

    localStorage.setItem('currentSurvey', JSON.stringify(questions));
    alert('问卷已成功保存！');
}

        // 发布功能
        async function publishSurvey() {
            try {
                // 获取问卷标题
                const surveyTitle = prompt("请输入问卷标题：");
                if (!surveyTitle) return;

                // 验证问题数据
                const questions = Array.from(document.querySelectorAll('.question-card')).map(card => {
                    const input = card.querySelector('.question-input');
                    if (!input.value.trim()) {
                        input.focus();
                        throw new Error('存在未填写的问题内容');
                    }

                    return {
                        type: card.querySelector('.question-type').textContent.includes('单选') ? 'single' :
                            card.querySelector('.question-type').textContent.includes('多选') ? 'multiple' : 'text',
                        text: input.value,
                        options: Array.from(card.querySelectorAll('.option-item input')).map(i => {
                            if (!i.value.trim()) {
                                i.focus();
                                throw new Error('存在未填写的选项内容');
                            }
                            return i.value;
                        })
                    };
                });

                // 发送请求
                const response = await fetch("{% url 'survey_create' %}", {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ title: surveyTitle, questions })
                });

                const result = await response.json();
                if (!response.ok) throw new Error(result.error || '发布失败');

                alert('问卷发布成功！');
                localStorage.removeItem('currentSurvey');
                window.location.href = "{% url 'survey_list' %}";
            } catch (error) {
                console.error('Error:', error);
                alert(`操作失败：${error.message}`);
            }
        }

        // 初始化加载保存的问卷
        document.addEventListener('DOMContentLoaded', () => {
            const savedSurvey = localStorage.getItem('currentSurvey');
            if (savedSurvey) {
                JSON.parse(savedSurvey).forEach(q => {
                    // 直接使用保存的英文标识
                    addQuestion(q.type); // q.type 已经是 singleChoice, multipleChoice 或 text
                    const card = document.querySelector(`#editArea .question-card:last-child`);
                    card.querySelector('.question-input').value = q.question;
                    q.options.forEach((opt, i) => {
                        if (card.querySelectorAll('.option-item').length <= i) {
                            addOption(card.querySelector('.ant-btn'));
                        }
                        card.querySelectorAll('.option-item input')[i].value = opt;
                    });
                });
            }
        });
    </script>
</body>
</html>